package org.melanesia.sql;

import java.sql.Connection;

import org.melanesia.beans.Mapper;


/**
 * This class is an entry point into SQLMapper framework.
 * It gives access to framework functionality such as creating SQL Queries or Stored Procedure Calls.
 * 
 * @author mkielar
 */
public final class SQLBuilder {

	/**
	 * Instance of database connection
	 */
	private Connection connection;
	
    /**
     * Instance of mapper
     */
    private Mapper mapper;
    
    /**
     * Constructs SQLBuilder with default SQLMapper.
     */
    public SQLBuilder(Connection connection) {
    	this(connection, new Mapper());
    }
    
    /**
     * Constructs SQLBuilder with specified SQLMapper.
     * @param sqlMapper
     */
    public SQLBuilder(Connection connection, Mapper mapper) {
    	this.connection = connection;
    	this.mapper = mapper;
    }
 
    /**
     * Returns this builder's data mapper
     * @return data mapper
     */
    public final Mapper getMapper() {
    	return mapper;
    }
    
    /**
     * Factory method for creating database queries
     * @param sql SQL query string
     * @return query object for further parameterization
     */
    public final Query createQuery(String sql) {
        return new Query(connection, mapper, sql);
    }
    
    /**
     * Factory method for creating database calls (stored procedures, etc.)
     * @param sql SQL query string
     * @return query object for further parameterization
     */
    public final Call createCall(String sql) {
        return new Call(connection, mapper, sql);
    }
    
    /**
     * Closes connection and makes this SQLBuilder unusable
     */
    public final void closeConnection() {
    	try { connection.close(); } catch (Throwable t) {}
    }
    
}
